package com.fin.zw.aiqas.util;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.Set;

/**
 * @Auther:
 * @Description:
 * @Date: 2019/10/31 17:01
 */
public class BeanUtil {

    /**
     * 拷贝对象（值为 null 的属性不覆盖）
     *
     * @param source
     * @param target
     */
    public static void copyProperties(Object source, Object target) {
        BeanUtils.copyProperties(source, target, getNullProperties(source));
    }

    /**
     * 获取传入对象为null的属性
     * @param source
     * @return
     */
    public static String[] getNullProperties(Object source) {
        BeanWrapper beanWrapper = new BeanWrapperImpl(source);
        PropertyDescriptor[] propertyDescriptors = beanWrapper.getPropertyDescriptors();
        Set<String> propertySet = new HashSet<>();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            Object propertyValue = beanWrapper.getPropertyValue(propertyDescriptor.getName());
            if (propertyValue == null) {
                propertySet.add(propertyDescriptor.getName());
            }
        }
        String[] propertyString = new String[propertySet.size()];
        return propertySet.toArray(propertyString);
    }
}
